/**
 * 
 */
package com.bolbachchan.blog.controller.posts;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bolbachchan.blog.controller.common.DefaultController;
import com.bolbachchan.blog.form.posts.NewPostForm;
import com.bolbachchan.blog.service.posts.UserPostsService;
import com.bolbachchan.blog.validator.posts.UserPostsValidator;
import com.bolbachchan.common.ui.Output;
import com.bolbachchan.common.ui.ScreenMessage.ScreenMessageType;

/**
 * @author Chaitanya
 * 
 */
@Controller
@RequestMapping(value = "pages/newPost")
public class NewPostController extends DefaultController<NewPostForm> {

    @Autowired
    private UserPostsService userPostsService;

    @Autowired
    private UserPostsValidator validator;

    /**
     * 
     */
    public NewPostController() {
    }

    @RequestMapping(method = RequestMethod.GET)
    public String viewNewPost(Model model, @ModelAttribute(FBB) NewPostForm fbb) {
	model.addAttribute(FBB, fbb);
	return NEW_POST_VIEW;
    }

    public @ResponseBody
    Output post(@ModelAttribute(FBB) NewPostForm fbb, BindingResult result) {
	validator.validate(fbb, result);
	if (result.hasErrors()) {
	    return messageUtils.getNewDefaultOutputWithMessage(ScreenMessageType.ERROR, NEW_POST_FAILURE_MESSAGE);
	}
	fbb.getPost().setUserDetails(getUser());
	userPostsService.saveNewPost(fbb.getPost());
	return messageUtils.getNewDefaultOutputWithMessage(ScreenMessageType.SUCCESS, NEW_POST_SUCCESS_MESSAGE);
    }
}
